package syb.radiation.plugin;

import com.zhny.aiot.plugin.ICenterFacilities;
import com.zhny.aiot.plugin.IDeviceFactory;
import com.zhny.aiot.plugin.core.model.IRequestMessage;
import com.zhny.aiot.plugin.modbus.ModemEngine;
import com.zhny.aiot.plugin.modbus.device.ModemConfig;
import com.zhny.aiot.plugin.modbus.device.modbus.ModbusNumDevice;
import com.zhny.aiot.plugin.modbus.handler.model.ModemResponseMessage;
import com.zhny.aiot.plugin.model.DeviceEntity;
import com.zhny.aiot.plugin.model.TaskEntity;
import io.netty.buffer.ByteBuf;
import syb.radiation.plugin.model.RadiationStoreEntry;

public class RadiationDevice extends ModbusNumDevice<RadiationStoreEntry> {
    public RadiationDevice(ModemEngine engine, IDeviceFactory<ModemConfig> factory, ICenterFacilities centerFacilities, DeviceEntity entity) {
        super (engine, factory, centerFacilities, entity);
    }

    @Override
    public RadiationStoreEntry decode(ModemResponseMessage msg) {
        logger.info("start syb radiation decode");
        ByteBuf buf = msg.getData();
        int radiation = buf.readUnsignedShort ();
        int sunshineDurationDay = buf.readUnsignedByte ();
        int sunshineDurationMonth = buf.readUnsignedShort ();
        int accumulatedRadiationDays = buf.readUnsignedByte ();
        int monthlyRadiationAccumulation = buf.readUnsignedByte ();
        RadiationStoreEntry entry = new RadiationStoreEntry();
        entry.setRadiationValue (String.format ("%d",radiation));
        entry.setSunshineDurationDay (String.format ("%.1f",sunshineDurationDay/360.0f));
        entry.setSunshineDurationMonth ( String.format ("%.1f",sunshineDurationMonth/36.0f));
        entry.setAccumulatedRadiationDays ( String.format ("%d",accumulatedRadiationDays*10000));
        entry.setMonthlyRadiationAccumulation ( String.format ("%d",monthlyRadiationAccumulation*100000));
        logger.info ("{}[{}]",this.entity.getName (),entry);
        return entry;
    }

    @Override
    public boolean checkError(ModemResponseMessage modemResponseMessage) {
        return modemResponseMessage.getData().readableBytes()== 8;
    }

    @Override
    protected IRequestMessage getCommand(TaskEntity taskEntity) {
        return getFactory().getRequestMessage(getConfig());
    }

    @Override
    protected void disposable() {

    }
}
